import json
import os
from PySide6.QtCore import QObject, Signal

class ThemeManager(QObject):
    theme_changed = Signal(str)  # 主题改变信号
    
    def __init__(self):
        super().__init__()
        self.config_dir = os.path.expanduser('~/.a-terminal/settings')
        self.config_file = os.path.join(self.config_dir, 'theme.json')
        self.ensure_config_file()
        self.load_config()
        
    def ensure_config_file(self):
        """确保配置文件存在"""
        os.makedirs(self.config_dir, exist_ok=True)
        if not os.path.exists(self.config_file):
            default_config = {
                'theme_mode': 'auto',  # 'auto', 'light', 'dark'
                'current_theme': 'dark'
            }
            with open(self.config_file, 'w', encoding='utf-8') as f:
                json.dump(default_config, f, ensure_ascii=False, indent=4)
                
    def load_config(self):
        """加载主题配置"""
        with open(self.config_file, 'r', encoding='utf-8') as f:
            self.config = json.load(f)
            
    def save_config(self):
        """保存主题配置"""
        with open(self.config_file, 'w', encoding='utf-8') as f:
            json.dump(self.config, f, ensure_ascii=False, indent=4)
            
    def get_theme_mode(self):
        """获取主题模式"""
        return self.config['theme_mode']
    
    def set_theme_mode(self, mode):
        """设置主题模式"""
        if mode in ['auto', 'light', 'dark']:
            self.config['theme_mode'] = mode
            self.save_config()
            if mode != 'auto':
                self.set_current_theme(mode)
            self.theme_changed.emit(self.get_current_theme())
            
    def get_current_theme(self):
        """获取当前主题"""
        return self.config['current_theme']
    
    def set_current_theme(self, theme):
        """设置当前主题"""
        if theme in ['light', 'dark']:
            self.config['current_theme'] = theme
            self.save_config()
            self.theme_changed.emit(theme)
    
    def get_available_themes(self):
        """获取可用的主题列表"""
        return ['light', 'dark']
            
    def get_theme_qss(self, theme=None):
        """获取主题QSS文件内容
        
        Args:
            theme: 主题名称，如果为None则使用当前主题
        """
        if theme is None:
            theme = self.get_current_theme()
        if theme not in self.get_available_themes():
            print(f"无效的主题名称: {theme}")
            return ""
        qss_file = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'static', 'css', f'{theme}.qss')
        try:
            with open(qss_file, 'r', encoding='utf-8') as f:
                return f.read()
        except Exception as e:
            print(f"加载QSS文件失败: {str(e)}")
            return ""